package com.cos.hospital.model;

import com.cos.hospital.code.Code;
import com.cos.hospital.code.Config;
import com.cos.hospital.model.connector.HttpMsgListener;
import com.cos.hospital.tool.ULog;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * @Description: 网络错误统一处理
 * @Author: Kosmos 接口 connector
 * @Date: 2018年10月17日 21:31
 * @Email: KosmoSakura@foxmail.com
 * @apiNote 还不完善。查漏补缺
 */
public class UHttp {
    public static <T> void start(Observable<T> observable, String describe, HttpMsgListener<T> listener) {
        Config.Describe = describe;
        observable.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<T>() {
                @Override
                public void onSubscribe(Disposable d) {
                    listener.onSubscribe(d);
                }

                @Override
                public void onNext(T dto) {
                    if (dto == null) {
                        listener.onError("网络异常，请稍后再试");
                    } else {
                        listener.onSuccess(dto);
//                        ULog.commonD(describe + "-->" + new Gson().toJson(dto));
                    }
                }

                @Override
                public void onError(Throwable e) {
                    listener.onError(Code.DefaultPrompt);//这里描述还需要确认，或者细分
                    listener.onFinish();
                    ULog.commonE(describe + "-->" + e.toString());
                }

                @Override
                public void onComplete() {
                    listener.onFinish();
                }
            });
    }

}
